function odd2Ascii()

inDir='C:\Users\matthew\Desktop\Projects\Oddball\PhaseAnalysis\oddballData\';
outDir='C:\Users\matthew\Desktop\Projects\Batch\';


bands={[4 8],[8 13],[13 22],[22 49]};
bandLabels={'theta','alpha','beta','gamma'};
nBands=length(bandLabels);

filter=fullfile(inDir,'*.ds');
files=dir(filter);
nSubjs=length(files);
nTrials=zeros(1,nSubjs);

for i=1:nSubjs
    subjName=files(i).name;
    trials=trial(fullfile(inDir,subjName),0)
    nTrials(i)=size(trials.trl,1);
end
minNTr=min(nTrials);
precision='%.20f';
for i=1:nSubjs
    subjName=files(i).name;
    trials=trial(fullfile(inDir,subjName),1);
    subjName=strtok(subjName,'.');
    for j=1:nBands   

        bf_trials=selectBand(trials,bands{j})
        
        outfile=strcat(bandLabels{j},'_');
        outfile=strcat(outfile,subjName);
        
        write2ascii(fullfile(outDir,outfile),bf_trials,minNTr,precision);
        
    end    
end

function [trials]=trial(filename,preproc)

% Band filtering
cfg= [];
% Set data
cfg.dataset= filename;
% Remove bad channels, set the trigger, set pre and post-stimulus interval
cfg.channel = {'MEG','-MLT22','-MLO42','-MLO43','-MRT22','-MRO42','-MRO43'};
cfg.trialdef.eventtype= 'OddAudio';  
%cfg.trialdef.eventvalue= eventValue;
cfg.trialdef.prestim= 1.5;
cfg.trialdef.poststim= 1.5;
%Call definetrial to compute trials

trials = ft_definetrial(cfg);
if(preproc)
    trials.continuous='yes';
    trials=ft_preprocessing(trials);
end
function [bf_trials]=selectBand(trials,band)

cfg = [];
cfg.channel= {'MEG','-MLT22','-MRT22'};
cfg.bpfilter='yes';
cfg.bpfreq=band;
bf_trials= ft_preprocessing(cfg,trials);
% function write2ascii(filename,trials,nTrials,precision)
% %write channel in column
% %nTrials=length(trials.trial);
% if(length(trials.trial)>= nTrials)
%     dlmwrite(filename, trials.trial{1}','delimiter','\t','precision',precision);%,'precision','%d'
% 
%     for i=2:nTrials
%         dlmwrite(filename,trials.trial{i}','-append','delimiter','\t','precision',precision);
%     end
% else
%     warning=strcat(filename,'--not enough trials')
% end
